<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container"
		style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<el-form-item>
							<el-button v-if="$hasPer('visitorManagement1:add')" @click="addNodeClick" icon="ele-Plus"
								type="primary"> 新增 </el-button>
							<el-button @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border
										element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55"
											:show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true"
											prop="fileOriginName" label="文件名称" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="fileSizeKb"
											label="文件大小kb" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true"
											prop="fileObjectName" label="存储名称" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true"
											prop="fileLocation" label="文件存储位置" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="i_Validity"
											label="观看有效期（月）" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="流程模板名称"
											align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true"
												label="流程模板名称" align="center">
												<template #header>
													<SearchModel typeId="n_FlcFlowschemeName" typeVal="input"
														@searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.n_FlcFlowschemeName }}
												</template>
											</el-table-column>
										</el-table-column>

										<el-table-column min-width="180" label="操作" align="center" fixed="right">
											<el-table-column min-width="180" fixed="right" align="center">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary"
														text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" class="clear-bg"
														text> 重置 </el-button>
												</template>
												<template #default="{ row }">
													<div class="operate-s">
														<el-button @click="lookVideo(row)" icon="ele-Edit"
															type="primary" text> 查看视频 </el-button>
														<!-- <el-button v-if="row.leaveTime === null && row.arriveTime === null" @click="editNodeClick(row)" icon="ele-Edit" type="primary" text> 入场 </el-button> -->
														<!-- <el-button  @click="editNodeClick(row)" icon="ele-Edit" type="primary" text> {{row.arriveTime && row.leaveTime === null?'退场' : '入场' }} </el-button> -->
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination v-model:currentPage="pageNo" v-model:page-size="pageSize"
									:total="totalRows" :page-sizes="[10, 20, 50, 100]" small background
									@size-change="handleSizeChange" @current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper" class="w-h-100" />
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible"
			title="新增" width="50%" @close="cancelUseClick">
			<el-form label-width="120px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="n_FlcFlowschemeId" label="流程模板">
							<el-select v-model="ruleForm.n_FlcFlowschemeId" class="m-2" placeholder="请选择流程模板"
								style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="i_Validity" label="观看有效期(月)">
							<el-input-number v-model="ruleForm.i_Validity" :min="1" :max="12" placeholder="请填写观看有效期"
								style="width: 100%" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-divider content-position="left"> 视频上传 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-upload ref="upload" action="#" v-model:file-list="fileList" :limit="1"
							:on-change="(file: any) => { handleChange(file) }" :auto-upload="false">
							<template #trigger>
								<el-button type="primary">选择视频</el-button>
							</template>
							<template #tip>
								<div class="el-upload__tip text-red">请选择mp4格式的视频，且只能上传一个视频，选择视频后确认信息无误后请点击确认按钮保存视频以及相关信息
								</div>
							</template>
						</el-upload>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 查看视频 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVideo"
			:title="videoOptions.name || '视频'" width="50%" @close="showDialogVideo = false">
			<video :src="videoOptions.url" />
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import { ElMessage, FormInstance, UploadInstance } from 'element-plus';
import { getVisitorRequestVideoListType, getVisitorVideoApi, downloadVideoTemplateApi } from '/@/api/sms/HazardousChemicalsInterface';
import { exportToExcel } from '/@/utils/exportToExcel';
import SearchModel from '/@/views/sms/component/search-model.vue';
import { getProcessTemplateApi } from '/@/api/workFlow';


const searchObj: any = reactive({});

const showDialogVideo = ref(false)
const videoOptions = reactive({
	url: "",
	name: ''
})
let baseUrl = import.meta.env.VITE_API_URL as any;

const lookVideo = async (row: any) => {
	// videoOptions.url = baseUrl  + '/Upload/SYS/' +  row.fileObjectName;
	// videoOptions.name = row.fileOriginName;   
	// showDialogVideo.value = true;
	const res = await downloadVideoTemplateApi({ n_FlcFlowschemeId: 540382871822405 })
	// console.log(JSON.stringify(res.data));
	// const url = window.URL.createObjectURL(res.data);
	// const a = document.createElement('a');
	// a.href = url;
	// a.download = 'video_template.webm';
	// a.click();
	// window.URL.revokeObjectURL(url);
	parseFile(res.data);
}

function parseFile(file) {
    const reader = new FileReader();
    reader.onload = function(e) {
        const arrayBuffer = file;
        parseMetadata(arrayBuffer);
    };
    reader.readAsArrayBuffer(file);
}

function parseMetadata(buffer) {
    // 这里可以使用库如 mp4box.js 来解析元数据
    // 下面是一个简化版的示例，仅用于展示
    let metadata = {};
    const view = new Uint8Array(buffer);

    // 简化解析过程，实际应使用更复杂的逻辑或库
    metadata.fileType = 'isom'; // 假设是标准的MP4文件
    metadata.creationTime = 0; // 示例值
	console.log(metadata,"metadata");
    // downloadMetadata(metadata);
}


/***** searchClick 查询按钮 *****/
const searchClick = () => {
	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};

/***** resetClick 重置按钮 *****/
const resetClick = () => {
	searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
			// console.log(i);
		});
	}
	initInfoFun();
};

const options1 = ref([]);


const showDialogVisible = ref(false);
const ruleForm: any = reactive({
	file: '',
	i_Validity: '1',
	n_FlcFlowschemeId: '',
});

/***** addNodeClick 新增 *****/
const addNodeClick = async () => {
	showDialogVisible.value = true;
};

/*** cancelUseClick  弹窗取消事件 */
const cancelUseClick = () => {
	showDialogVisible.value = false;
	ruleForm.file = '';
	ruleForm.i_Validity = '1';
	ruleForm.n_FlcFlowschemeId = '';
	fileList.value = [];
	upload.value?.clearFiles();
};

/*** controlUseClick  弹窗提交事件 */
const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	if (!ruleForm.file.length) return ElMessage.error('请上传视频');
	await formEl.validate((valid, fields) => {
		if (valid) {
			getVisitorVideoApi(ruleForm).then((res) => {
				console.log(res);
				cancelUseClick();
				getData();
			});
		} else {
			console.log('error submit!', fields);
		}
	});
};

/*** ruleFormRef  表单校验 */
const ruleFormRef = ref();
const rules = reactive({
	i_Validity: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' },
	],
	n_FlcFlowschemeId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});



//上传视频
const upload = ref<UploadInstance>();
const fileList = ref([]);
const handleChange = (uploadFile: any) => {
	const videoType = uploadFile.name.split('.')[1];
	if (videoType != 'mp4') return ElMessage.error('请上传mp4格式的视频');
	console.log(uploadFile);
	ruleForm.file = [uploadFile.raw];
};


onMounted(async () => {
	await initInfoFun();

	const res = await getProcessTemplateApi({ SchemeTypeCode: 'VistorApplyFlow' });
	options1.value = res.data.map((item: any) => {
		return {
			label: item.schemeName,
			value: item.id,
		};
	});
});


/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'n_FlcFlowschemeName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'N_FlcFlowschemeName', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '流程模板名称', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};
const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};


/*** ================================= 导出数据函数操作 ================================= */
const excelRef: any = ref(null);
const handleExport = () => {
	if (excelRef.value) {
		if (excelRef.value.data.length !== 0) {
			let tableExcel: any = [];
			let tableArr = excelRef.value.data;
			tableArr.map((item: any) => {
				let tableObj: any = {};
				tableObj['文件名称'] = item.fileOriginName ? item.fileOriginName : '-';
				tableObj['文件大小kb'] = item.fileSizeKb ? item.fileSizeKb : '-';
				tableObj['存储名称'] = item.fileObjectName ? item.fileObjectName : '-';
				tableObj['文件存储位置'] = item.fileLocation ? item.fileLocation : '-';
				tableObj['观看有效期（月）'] = item.i_Validity ? item.i_Validity : '-';
				tableObj['流程模板名称'] = item.n_FlcFlowschemeName ? item.n_FlcFlowschemeName : '-';
				tableExcel.push(tableObj);
			});
			exportToExcel(tableExcel, '访客视频记录.xlsx');
		} else {
			ElMessage({
				type: 'error',
				message: '暂无数据导出',
			});
		}
	}
};

const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getVisitorRequestVideoListType, {}, searchObj);
</script>

<style lang="scss">
@import '../../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	:deep(.el-upload--picture-card) {
		--el-upload-picture-card-size: 90px;
		background-color: #cccccc56;
		margin-bottom: 2px;
	}

	:deep(.el-upload-list__item) {
		width: 90px;
		height: 90px;
	}

	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}

	.cardBox {
		margin: 6px;
		width: 100%;
		height: 100%;
		border: 1px solid #ccc;

		.cardOne {
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1px solid #ccc;
			width: 100%;
			height: 40px;

			li {
				display: flex;
				align-items: center;

				&:nth-child(1) {
					display: flex;
					width: 50%;

					span {
						padding: 0 4px;
						width: 70px;
					}

					p {
						flex: 1;
					}
				}

				&:nth-child(2) {
					display: flex;
					width: 50%;

					span {
						padding: 0 4px;
						width: 70px;
					}

					p {
						flex: 1;
					}
				}
			}
		}

		.cardTwo {
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1px solid #ccc;
			width: 100%;
			height: 200px;

			li {
				display: flex;
				align-items: center;

				&:nth-child(1) {
					display: flex;
					width: 50%;

					span {
						padding: 0 4px;
						width: 70px;
					}

					p {
						flex: 1;
					}
				}

				&:nth-child(2) {
					display: flex;
					width: 50%;

					span {
						padding: 0 4px;
						width: 70px;
					}

					p {
						flex: 1;
					}
				}
			}
		}

		.cardThree {
			display: flex;
			justify-content: center;
			align-items: center;
			border-bottom: 1px solid #ccc;
			width: 100%;
			height: 100px;

			p {
				&:nth-child(1) {
					padding: 0 4px;
					width: 70px;
				}

				&:nth-child(2) {
					flex: 1;
					text-align: center;

					.upload-s {
						width: 100%;
						height: 100%;
					}
				}
			}
		}

		.cardFour {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 40px;

			p {
				&:nth-child(1) {
					padding: 0 4px;
					width: 70px;
				}

				&:nth-child(2) {
					flex: 1;
					text-align: center;
				}
			}
		}
	}
}
</style>
